import { ref } from "vue";
/**
 *
 * @param {()=>Function} callback 回调函数 需要返回一个请求函数
 * @param {Object} options 配置项
 * @param {boolean} options.immediate 是否立即执行
 * @returns
 */
export default function useFetchData(callback, options = {}) {
  const defaultOptions = { immediate: false };
  options = { ...defaultOptions, ...options };
  const data = ref(null);
  const loading = ref(false);
  const error = ref(null);
  if (options.immediate) {
    run();
  }

  const executor = () => {
    run();
  };
  function run() {
    loading.value = true;
    callback()
      .then(
        (value) => {
          data.value = value;
        },
        (err) => {
          error.value = err;
        }
      )
      .finally(() => {
        loading.value = false;
      });
  }
  return { data, loading, error, executor };
}
